package com.tms.admin.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.hash.Hash;
import com.tms.admin.handler.TMSException;
import com.tms.admin.service.CaptchaService;
import com.tms.common.entity.ResultCode;
import com.tms.common.entity.ResultVO;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/*-----------------------------------
 *   @Time: 2022/9/8 21:23
 *   @Description: 验证码
-----------------------------------*/
@Service
public class CaptchaServiceImpl implements CaptchaService {
    // 记录当前用户验证码的缓存
    private final static Map<String, String> captchaCache = new HashMap<>();
    @Override
    public String getCode(String username) {
        /**
         *  Step 1. 调用 hutool 库生成验证码
         *  Step 2. 将验证码的值保存到 缓存
         *  Step 3. 返回验证码图片的 base64 数据
         */
        // Step 1
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(80, 40, 4, 5);
        // Step 2
        captchaCache.put(username, lineCaptcha.getCode());
        // Step 3
        String captcha = lineCaptcha.getImageBase64Data();
        return captcha;
    }

    @Override
    public void verify(String username, String captcha) {
        /**
         * Step 1. 从 缓存 获取服务器保存的验证码
         * Step 2. 判断服务器保存的验证码是否为空
         * Step 3. 判断验证码是否匹配
         */
        // Step 1
        String realCaptcha = captchaCache.get(username);
        // Step 2
        if(StringUtils.isEmpty(realCaptcha)) {
            throw new TMSException(ResultCode.FAIL, "服务器验证码为空");
        }
        // Step 3
        if(!realCaptcha.equals(captcha)){
            throw new TMSException(ResultCode.FAIL, "验证码错误");
        }
    }
}
